package com.cqvip.innocence.project.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqvip.innocence.common.annotation.Log;
import com.cqvip.innocence.framework.jwt.service.AdminTokenService;
import com.cqvip.innocence.project.controller.AbstractController;
import com.cqvip.innocence.project.model.dto.JsonResult;
import com.cqvip.innocence.project.model.dto.router.Routers;
import com.cqvip.innocence.project.model.entity.Admin;
import com.cqvip.innocence.project.model.entity.Resource;
import com.cqvip.innocence.project.model.entity.Role;
import com.cqvip.innocence.project.model.entity.RoleResource;
import com.cqvip.innocence.project.model.enums.BusinessType;
import com.cqvip.innocence.project.model.enums.MenuType;
import com.cqvip.innocence.project.service.ResourceService;
import com.cqvip.innocence.project.service.RoleResourceService;
import com.cqvip.innocence.project.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Innocence
 * @since 2020-07-13
 */
@RestController
@RequestMapping("/${base-url.system}/resource/")
@Api(tags = "权限和路由资源操作接口")
public class ResourceController extends AbstractController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private RoleResourceService roleResourceService;

    @Autowired
    private AdminTokenService tokenService;


    @GetMapping("getRoutersByRole")
    @ApiOperation("根据角色获取对应的路由用于前端做菜单,只需要管理员id和用户名为参数")
    public JsonResult getRoutersByRole() {
        Admin admin = tokenService.getLoginAdmin().getAdminUser();
        List<Role> roles = roleService.getRolesByAdmin(admin);
        List<Resource> resources = new ArrayList<>();
        for (Role role : roles) {
            List<Resource> resourcesByRoleId = resourceService.getResourcesByRoleId(role);
            if (!resourcesByRoleId.isEmpty()) {
                for (Resource r : resourcesByRoleId) {
                    if (!r.getMenuType().equals(MenuType.F)) {
                        resources.add(r);
                    }
                }
            }
        }
        List<Resource> collect = resources.stream().distinct().collect(Collectors.toList());
        List<Routers> routers = resourceService.processRouter(collect);
        JsonResult get = JsonResult.Get();
        get.setSuccess(true);
        get.putList(routers);
        return get;
    }

    @PostMapping("getResourceByRole")
    @ApiOperation("根据角色获取对应的资源,只需要管理员id和用户名为参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "admin.id", value = "管理员id", dataTypeClass = Long.class, required = true),
            @ApiImplicitParam(name = "admin.name", value = "管理员用户名", dataTypeClass = String.class, required = true),
    })
    public JsonResult getResourceByRole(Admin admin) {
        List<Role> roles = roleService.getRolesByAdmin(admin);
        List<Resource> resources = new ArrayList<>();
        for (Role role : roles) {
            List<Resource> resourcesByRoleId = resourceService.getResourcesByRoleId(role);
            if (!resourcesByRoleId.isEmpty()) {
                for (Resource r : resourcesByRoleId) {
                    resources.add(r);
                }
            }
        }
        JsonResult get = JsonResult.Get();
        get.setSuccess(true);
        get.putList(resources);
        return get;
    }

    @GetMapping("getResourcesPage")
    @ApiOperation("获取所有resource分页")
    @Log(title = "获取所有resource分页", businessType = BusinessType.SELECT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "menuType", value = "资源类型", dataTypeClass = MenuType.class),
            @ApiImplicitParam(name = "name", value = "资源名称", dataTypeClass = String.class),
            @ApiImplicitParam(name = "sort", value = "排序，true标识按排序字段升序，false为降序", dataTypeClass = Boolean.class)
    })
    public JsonResult getResources(MenuType menuType, String name, Boolean sort) {
        Page page = getPageParams();
        LambdaQueryWrapper<Resource> wrapper = new QueryWrapper<Resource>().lambda();
        if (null != menuType) {
            wrapper.eq(Resource::getMenuType, menuType);
        }
        if (!StringUtils.isBlank(name)) {
            wrapper.eq(Resource::getName, name);
        }
        if (sort != null) {
            if (sort == true) {
                wrapper.orderByAsc(Resource::getSort);
            } else {
                wrapper.orderByDesc(Resource::getSort);
            }
        }
        Page<Resource> resources = resourceService.page(page, wrapper);
        return JsonResult.Get("page", resources);
    }

    @GetMapping("getAllResourceList")
    @ApiOperation("获取所有资源列表")
    public JsonResult getResourceToRole() {
        List<Resource> list = resourceService.list();
        JsonResult get = JsonResult.Get(true);
        get.putList(list);
        return get;
    }

    @PostMapping("saveOrEdit")
    @ApiOperation("新增或者编辑resource")
    @Log( title = "新增或者编辑resource",businessType = BusinessType.SAVE_OR_UPDATE)
    public JsonResult saveOrEdit(Resource resource){
        if (resource.getParentId()!=null && resource.getParentId()==0){
            resource.setParentId(null);
        }
        resourceService.saveOrUpdate(resource);
        return JsonResult.Get(true);
    }

    @PostMapping("delete")
    @ApiOperation("根据id批量删除资源权限;参数名：deleteIds，含义：需要删除的资源id集合")
    @Log(title = "新增或者编辑resource", businessType = BusinessType.DELETE, isSaveRequestData = true)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deleteIds", value = "需要删除的资源id集合", dataTypeClass = Long.class, required = true)
    })
    public JsonResult delete(@RequestBody List<Long> deleteIds) {
        deleteIds.forEach(item -> {
            LambdaQueryWrapper<RoleResource> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RoleResource::getResourceId, item);
            roleResourceService.remove(wrapper);
        });
        boolean b = resourceService.removeByIds(deleteIds);
        JsonResult get = JsonResult.Get(b);
        if (b) {
            get.setMsg("删除成功，共删除：" + deleteIds.size() + "条数据!");
        }
        return get;
    }

    /**
     * 获取所有菜单资源(树状结构)
     *
     * @return
     */
    @ApiOperation("获取所有菜单资源(树状结构)")
    @GetMapping("getTreeDataOfResources")
    public JsonResult getTreeDataOfResources() {
        List<Resource> resources = resourceService.list().stream().sorted(Comparator.comparing(Resource::getSort)).collect(Collectors.toList());
        List<Routers> routers = resourceService.processRouter(resources);
        return JsonResult.Get().putList(routers);
    }
}

